#! /usr/bin/python3
# -*- coding: utf-8 -*-

import pickle
import sys
import os

filename = 'address_book.data'

class people(dict):
	def __init__(self, name, phone, mail):
		dict.__init__({})
		self.name = name
		self.phone = phone
		self.mail = mail

# 定义读取文件函数
def f_load(filename):
	with open(filename,'rb') as fl:
		address_data = pickle.load(fl)
	return (address_data)


# 定义保存文件函数
def f_dump(people_data ,filename):
	with open(filename,'wb') as fl:
		pickle.dump(people_data,fl)
		

# 浏览联系人
def browse():
	a_data = f_load(filename)
	print("联系人名单：")
	for each_person in a_data.items():
		print(each_person)
	print()
	del a_data

# 添加联系人
def add():
	print("按下列格式输入联系人：jack,145632012,123@gmail.com ")
	enterd = input().split(',')
	person = people(enterd[0],enterd[1],enterd[2])
	a_data = f_load(filename)
	a_data[person.name] = str(person.phone) + ", " + str(person.mail)
	f_dump(a_data, filename)
	print('添加成功')
	print()
	del a_data
	del person


# 修改联系人
def modify():
	a_data = f_load(filename)
	name_find = input('请输入用户名字：')
	if name_find in a_data:
		del a_data[name_find]
		del a_data
		add()
	else:
		print("没有找到该联系人")
		del a_data
	del name_find

# 删除联系人
def delete():
	a_data = f_load(filename)
	d_name = str(input('请输入要删除人的名字：'))
	if d_name in a_data:
		del a_data[d_name]
		f_dump(a_data, filename)
		print('删除成功')
		print()
	else:
		print('没有该联系人，请重新输入')
		print()
		delete()
	del d_name
	del a_data

# 搜索联系人
def search():
	a_data = f_load(filename)
	name_find = input('请输入用户名字：')
	if name_find in a_data:
		print(name_find+': '+a_data[name_find])
	else:
		print("没有找到该联系人")
	print()
	del a_data
	del name_find

def main():
	enter = int(input("输入对应数字执行你需要的操作：1-浏览;2-搜索；3-添加；4-删除；5-修改;6-退出\n"))
	if enter == 1:
		browse()
		main()
	elif enter == 2:
		search()
		main()
	elif enter == 3:
		add()
		main()
	elif enter == 4:
		delete()
		main()
	elif enter == 5:
		modify()
		main()
	elif enter == 6:
		sys.exit()
		main()
	else:
		print("输入有误\n")
		main()

if os.path.exists('address_book.data'):
	main()
else:
	print("请按下列格式输入联系人：jack,145632012,123@gmail.com ")
	enterd = input().split(',')
	person = people(enterd[0],enterd[1],enterd[2])
	address_data = {person.name: person.phone+", "+person.mail}
	f_dump(address_data,filename)
	del address_data
	del person
	main()



